package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.mapper.AdUserDao;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.LogicException;
import com.heima.common.exception.ParamException;
import com.heima.model.admin.dto.AdUserLoginDto;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service("adUserService")
public class AdUserServiceImpl implements AdUserService {
    @Resource
    private AdUserDao adUserDao;

    @Override
    public Map<String, Object> login(AdUserLoginDto dto) {
        //1. 校验参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            throw new ParamException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 根据用户输入的用户名查询数据库用户信息  WmUser
        AdUser adUser = adUserDao.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getUsername, dto.getName()));

        if (adUser == null) {
            throw new LogicException(AppHttpCodeEnum.LOGIN_PARAM_ERROR);
        }

        //3. 使用数据库保存的盐 + 用户输入的密码 加密得到密文 , 使用密文和数据库中的密文进行比对
        String pwd = DigestUtils.md5Hex(dto.getPassword() + adUser.getSalt());
        if (!StringUtils.equals(pwd, adUser.getPassword())) {
            throw new LogicException(AppHttpCodeEnum.LOGIN_PARAM_ERROR);
        }
        //4. 使用JWT生成TOKEN ,返回数据
        String token = AppJwtUtil.getToken(adUser.getId());

        Map<String, Object> result = new HashMap<>();
        adUser.setSalt("");
        adUser.setPassword("");
        result.put("user", adUser);
        result.put("token", token);

        return result;
    }
}
